package file;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * PDF文件抽取成图片
 */
public class Pdf2Image {


    public static void main(String[] args) {
        PdfToImages("E:\\xx.pdf", "F:\\output");
    }


    /**
     * PDF文件转图片
     *
     * @param inputfile       PDF文件地址
     * @param outputDirectory 输出目录路径
     */
    public static List<String> PdfToImages(String inputfile, String outputDirectory) {

        List<String> result = new ArrayList<String>();

        try {
            //判断临时文件目录是否存在
            File file = new File(outputDirectory);
            if (!file.exists()) {
                file.mkdir();
            }
            PDDocument doc = PDDocument.load(new File(inputfile));
            int pageCount = doc.getNumberOfPages();
            PDFRenderer pdfRenderer = new PDFRenderer(doc);

            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = pdfRenderer.renderImageWithDPI(i, 150);
                Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("png");
                ImageWriter writer = iter.next();

                //本地生成临时文件
                File outFile = new File(outputDirectory + "/" + i + ".png");
                FileOutputStream out = new FileOutputStream(outFile);
                ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
                writer.setOutput(outImage);
                writer.write(new IIOImage(image, null, null));
                //关闭文件流并删除文件
                out.close();
                outImage.close();

            }
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
